<template>
  <view class="dashboard-container">
    <view class="stats-cards">
      <view class="stat-card">
        <view class="card-header">
          <text class="card-title">会话统计</text>
          <text class="card-period">今日</text>
        </view>
        <view class="card-body">
          <view class="stat-value primary">{{ dashboardData.todaySessions || 0 }}</view>
          <view class="stat-label">会话总数</view>
          <view class="stat-trend" :class="{'up': dashboardData.sessionTrend > 0, 'down': dashboardData.sessionTrend < 0}">
            <text class="trend-icon">{{ dashboardData.sessionTrend > 0 ? '↑' : '↓' }}</text>
            <text class="trend-value">{{ Math.abs(dashboardData.sessionTrend || 0) }}%</text>
            <text class="trend-label">较昨日</text>
          </view>
        </view>
      </view>
      
      <view class="stat-card">
        <view class="card-header">
          <text class="card-title">用户统计</text>
          <text class="card-period">今日</text>
        </view>
        <view class="card-body">
          <view class="stat-value success">{{ dashboardData.todayUsers || 0 }}</view>
          <view class="stat-label">访问用户数</view>
          <view class="stat-trend" :class="{'up': dashboardData.userTrend > 0, 'down': dashboardData.userTrend < 0}">
            <text class="trend-icon">{{ dashboardData.userTrend > 0 ? '↑' : '↓' }}</text>
            <text class="trend-value">{{ Math.abs(dashboardData.userTrend || 0) }}%</text>
            <text class="trend-label">较昨日</text>
          </view>
        </view>
      </view>
      
      <view class="stat-card">
        <view class="card-header">
          <text class="card-title">客服统计</text>
          <text class="card-period">实时</text>
        </view>
        <view class="card-body">
          <view class="stat-value warning">{{ dashboardData.activeCustomerService || 0 }}</view>
          <view class="stat-label">在线客服</view>
          <view class="stat-detail">
            <text>总数：{{ dashboardData.totalCustomerService || 0 }}</text>
          </view>
        </view>
      </view>
      
      <view class="stat-card">
        <view class="card-header">
          <text class="card-title">响应时间</text>
          <text class="card-period">今日</text>
        </view>
        <view class="card-body">
          <view class="stat-value info">{{ dashboardData.avgResponseTime || '0s' }}</view>
          <view class="stat-label">平均响应时间</view>
          <view class="stat-trend" :class="{'up': dashboardData.responseTrend < 0, 'down': dashboardData.responseTrend > 0}">
            <text class="trend-icon">{{ dashboardData.responseTrend < 0 ? '↑' : '↓' }}</text>
            <text class="trend-value">{{ Math.abs(dashboardData.responseTrend || 0) }}%</text>
            <text class="trend-label">较昨日</text>
          </view>
        </view>
      </view>
    </view>
    
    <view class="charts-container">
      <view class="chart-card weekly-sessions">
        <view class="card-header">
          <text class="card-title">近7天会话数量</text>
        </view>
        <view class="card-body">
          <qiun-data-charts 
            type="column"
            :chartData="weeklySessionsChart"
            background="none"
          />
        </view>
      </view>
      
      <view class="chart-card service-distribution">
        <view class="card-header">
          <text class="card-title">会话分布</text>
        </view>
        <view class="card-body">
          <qiun-data-charts 
            type="pie"
            :chartData="serviceDistributionChart"
            background="none"
          />
        </view>
      </view>
    </view>
    
    <view class="active-sessions">
      <view class="section-header">
        <text class="section-title">活跃会话</text>
        <navigator url="/pages/customer-service/list" class="view-more">查看更多</navigator>
      </view>
      
      <view class="session-list" v-if="dashboardData.activeSessions && dashboardData.activeSessions.length > 0">
        <view class="session-item" v-for="(session, index) in dashboardData.activeSessions" :key="index">
          <view class="session-user">
            <view class="avatar" :style="{ backgroundColor: getAvatarColor(session.userId) }">
              {{ session.username ? session.username.charAt(0).toUpperCase() : 'U' }}
            </view>
            <view class="user-info">
              <text class="username">{{ session.username || '访客' + session.userId }}</text>
              <text class="time">{{ formatTime(session.startTime) }}</text>
            </view>
          </view>
          <view class="session-type" :class="{ 'human': session.serviceType === 'human', 'bot': session.serviceType === 'bot' }">
            {{ session.serviceType === 'human' ? '人工' : '机器人' }}
          </view>
          <view class="session-actions">
            <button size="mini" @click="viewSession(session.id)">查看</button>
          </view>
        </view>
      </view>
      <view class="empty-state" v-else>
        <text>暂无活跃会话</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getCurrentInstance } from 'vue'

export default {
    data() {
      return {
        dashboardData: {
          todaySessions: 0,
          sessionTrend: 0,
          todayUsers: 0,
          userTrend: 0,
          activeCustomerService: 0,
          totalCustomerService: 0,
          avgResponseTime: '0s',
          responseTrend: 0,
          activeSessions: [],
          weeklySessions: {
            dates: [],
            counts: []
          },
          serviceDistribution: {
            human: 0,
            bot: 0
          }
        },
        // 近7天会话数量图表
        weeklySessionsChart: {
          categories: [],
          series: [
            {
              name: "会话数",
              data: []
            }
          ]
        },
        // 会话分布图表
        serviceDistributionChart: {
          series: [
            {
              name: "会话分布",
              data: [
                {name: "人工客服", value: 0},
                {name: "机器人", value: 0}
              ]
            }
          ]
        },
        refreshTimer: null,
        api: null
      }
    },
    created() {
      const { proxy } = getCurrentInstance()
      this.api = proxy.$api
      this.fetchDashboardData()
      this.startAutoRefresh()
    },
    beforeDestroy() {
      this.stopAutoRefresh()
    },
    methods: {
      // 获取仪表盘数据
      async fetchDashboardData() {
        try {
          const res = await this.api.dashboard.getDashboardData()
          if (res.code === 200 && res.data) {
            // 更新仪表盘数据
            this.dashboardData = {
              ...this.dashboardData,
              ...res.data
            }
            
            // 更新近7天会话图表数据
            if (res.data.weeklySessions) {
              this.updateWeeklySessionsChart(res.data.weeklySessions)
            }
            
            // 更新会话分布图表数据
            if (res.data.serviceDistribution) {
              this.updateServiceDistributionChart(res.data.serviceDistribution)
            }
          } else {
            uni.showToast({
              title: res.message || '获取仪表盘数据失败',
              icon: 'none'
            })
          }
        } catch (err) {
          uni.showToast({
            title: '获取仪表盘数据失败',
            icon: 'none'
          })
        }
      },
      
      // 开始自动刷新
      startAutoRefresh() {
        this.refreshTimer = setInterval(() => {
          this.fetchDashboardData()
        }, 60000) // 每60秒刷新一次
      },
      
      // 停止自动刷新
      stopAutoRefresh() {
        if (this.refreshTimer) {
          clearInterval(this.refreshTimer)
          this.refreshTimer = null
        }
      },
      
      // 查看会话详情
      viewSession(sessionId) {
        uni.navigateTo({
          url: `/pages/customer-service/dashboard?sessionId=${sessionId}`
        })
      },
      
      // 格式化时间
      formatTime(timestamp) {
        if (!timestamp) return '-'
        const date = new Date(timestamp)
        return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
      },
      
      // 根据用户ID生成头像颜色
      getAvatarColor(userId) {
        if (!userId) return '#8c8c8c'
        
        const colors = [
          '#1677ff', '#13c2c2', '#52c41a', '#faad14', 
          '#722ed1', '#eb2f96', '#fadb14', '#a0d911'
        ]
        
        const id = parseInt(userId.toString().replace(/[^\d]/g, '')) || 0
        return colors[id % colors.length]
      },
      
      // 更新近7天会话图表数据
      updateWeeklySessionsChart(data) {
        this.weeklySessionsChart.categories = data.dates || []
        this.weeklySessionsChart.series[0].data = data.counts || []
      },
      
      // 更新会话分布图表数据
      updateServiceDistributionChart(data) {
        this.serviceDistributionChart.series[0].data = [
          {name: "人工客服", value: data.human || 0},
          {name: "机器人", value: data.bot || 0}
        ]
      }
    }
  }
</script>

<style lang="scss">
  .dashboard-container {
    padding: 20px;
    
    .stats-cards {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      margin-bottom: 20px;
      
      .stat-card {
        flex: 1;
        min-width: 220px;
        background-color: #fff;
        border-radius: 8px;
        padding: 15px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        
        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;
          
          .card-title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
          }
          
          .card-period {
            font-size: 12px;
            color: #999;
            background-color: #f5f5f5;
            padding: 2px 8px;
            border-radius: 10px;
          }
        }
        
        .card-body {
          .stat-value {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 5px;
            
            &.primary { color: #1677ff; }
            &.success { color: #52c41a; }
            &.warning { color: #faad14; }
            &.info { color: #13c2c2; }
          }
          
          .stat-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 10px;
          }
          
          .stat-trend {
            display: flex;
            align-items: center;
            font-size: 12px;
            
            &.up {
              color: #52c41a;
            }
            
            &.down {
              color: #f5222d;
            }
            
            .trend-icon {
              margin-right: 4px;
            }
            
            .trend-value {
              font-weight: bold;
              margin-right: 4px;
            }
            
            .trend-label {
              color: #999;
            }
          }
          
          .stat-detail {
            margin-top: 10px;
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
    
    .charts-container {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      margin-bottom: 20px;
      
      .chart-card {
        background-color: #fff;
        border-radius: 8px;
        padding: 15px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        
        &.weekly-sessions {
          flex: 2;
          min-width: 500px;
        }
        
        &.service-distribution {
          flex: 1;
          min-width: 300px;
        }
        
        .card-header {
          margin-bottom: 15px;
          
          .card-title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
          }
        }
        
        .card-body {
          height: 280px;
        }
      }
    }
    
    .active-sessions {
      background-color: #fff;
      border-radius: 8px;
      padding: 15px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        
        .section-title {
          font-size: 16px;
          font-weight: bold;
          color: #333;
        }
        
        .view-more {
          font-size: 14px;
          color: #1677ff;
        }
      }
      
      .session-list {
        .session-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 12px 0;
          border-bottom: 1px solid #f0f0f0;
          
          &:last-child {
            border-bottom: none;
          }
          
          .session-user {
            display: flex;
            align-items: center;
            flex: 1;
            
            .avatar {
              width: 40px;
              height: 40px;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 18px;
              font-weight: bold;
              color: #fff;
              margin-right: 12px;
            }
            
            .user-info {
              .username {
                font-size: 14px;
                font-weight: bold;
                color: #333;
                display: block;
              }
              
              .time {
                font-size: 12px;
                color: #999;
              }
            }
          }
          
          .session-type {
            padding: 2px 10px;
            border-radius: 12px;
            font-size: 12px;
            margin-right: 20px;
            
            &.human {
              background-color: #e6f7ff;
              color: #1677ff;
            }
            
            &.bot {
              background-color: #f6ffed;
              color: #52c41a;
            }
          }
        }
      }
      
      .empty-state {
        padding: 40px 0;
        text-align: center;
        color: #999;
      }
    }
  }
  
  @media (max-width: 768px) {
    .dashboard-container {
      padding: 10px;
      
      .stats-cards, .charts-container {
        gap: 10px;
      }
      
      .stat-card, .chart-card, .active-sessions {
        margin-bottom: 10px;
      }
      
      .charts-container .chart-card {
        flex: 1 1 100%;
        min-width: 100%;
        
        .card-body {
          height: 220px;
        }
      }
    }
  }
</style> 